package com.whut.manage;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.apache.tomcat.websocket.server.WsSci;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
@Slf4j
@SpringBootApplication
@EnableScheduling
public class ManageApplication {



    public static void main(String[] args) {
        SpringApplication.run(ManageApplication.class, args);
    }





    /*
    * 在这里设置http的监听端口为80端口,http默认端口,这样在访问的时候也可以不用带上端口号.
完成以上配置后,我们访问 http://localhost 即可自动跳转为 https://localhost
链接：https://www.jianshu.com/p/8d4aba3b972d
    * */

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

    private Connector redirectConnector() {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(8078);
        connector.setSecure(false);
        connector.setRedirectPort(8086);
        return connector;
    }



/*
*
*   下面方法可以开启 ws转wss
*
* */
    @Bean
    public TomcatContextCustomizer tomcatContextCustomizer() {
        log.info("init");
        return new TomcatContextCustomizer() {
            @Override
            public void customize(Context context) {
                log.info("init   customize");
                context.addServletContainerInitializer(new WsSci(), null);
            }
        };
    }

}
